package com.luo.auth.service.impl;

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.luo.auth.constant.Constants;
import com.luo.auth.dao.RedisDao;
import com.luo.auth.pojo.TokenObj;
import com.luo.auth.service.TokenService;

@Service
public class TokenServiceImpl implements TokenService{
	private Logger logger = LoggerFactory.getLogger( TokenServiceImpl.class );

    @Autowired
    private RedisDao redisDao;

    @Override
    public TokenObj createToken(long id, int source) {
        try {
            // 使用 uuid 作为源 token
            String token = UUID.randomUUID().toString().replace( "-", "" );
            TokenObj model = new TokenObj( id, source, token );
            // 存储到 redis 并设置过期时间
            redisDao.set(model.getRedisKey(), token, Constants.TOKEN_EXPIRES_MINUTE );
            return model;
        } catch (Exception e) {
            logger.error( "createToken----------" + e.getMessage() );
            return null;
        }
    }

    @Override
    public int checkToken( TokenObj model ) {
        try {
            Object token = redisDao.get( model.getRedisKey()  );
            if (token == null) {
                return 0;
            }else{
                if (token.equals( model.getToken() )) {
                    // 如果验证成功，说明此用户进行了一次有效操作，延长 token 的过期时间
                    redisDao.getAndUpdateTime( model.getRedisKey()  );
                    return 1;
                }else{
                    return 2;
                }
            }
        } catch (Exception e) {
            logger.error( "checkToken----------" + e.getMessage() );
            return 0;
        }
    }

    @Override
    public TokenObj getToken( String authentication ) {
        if (authentication == null || authentication.length() == 0) {
            return null;
        }
        String[] param = authentication.split( "_" );
        if (param.length != 3) {
            return null;
        }
        // 使用 userId 和源 token 简单拼接成的 token，可以增加加密措施
        Long userId = Long.parseLong( param[0] );
        Integer source = Integer.parseInt( param[1] );
        String token = param[2];
        return new TokenObj( userId, source, token );
    }

    @Override
    public void deleteToken( String key ) {
        try {
            redisDao.delete( key );
        } catch (Exception e) {
            logger.error( "deleteToken----------" + e.getMessage() );

        }
    }
}
